import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

@Component({
	selector: 'sa-garbage-single',
	templateUrl: './garbage-single.component.html',
})
export class GarbageSingleComponent implements OnInit {
	tableData = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	startTime_table:string = '';
	endTime_table:string = '';
	selectedCompanyId:string = '';
	selectedCompanyName:string = '';
	carNumber:string = '';
	deviceId:string = '';
	timeType:string='1'; //时间类型
	specifyTime = {
        startTime: '',
        endTime: '',
	}
	jumpData:any; // 跳转页面接收到的数据
	constructor(private jsonApiService: JsonApiService, private router: Router,private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
			//从地磅数据验证跳转过来
            if (common.getCookie('weighbridgeDataResult')) {
				this.jumpData = JSON.parse(common.getCookie('weighbridgeDataResult'));
                common.clearCookie('weighbridgeDataResult');
            }
		});
	}

	ngOnInit() {
		this.initBtn();
		var that = this;
	    let timeR = common.getRecentDaysDateTime(1);
        this.specifyTime = {
            startTime: timeR.startTime,
            endTime: timeR.endTime,
        }
        setTimeout(()=>{
            //是否是携带过来的参数
            if(that.jumpData&&that.jumpData.deviceId){
                that.startTime_table = that.jumpData.transportStartDate;
                that.endTime_table = that.jumpData.transportEndDate;
                $('#datetimepicker1').val(that.startTime_table);
                $('#datetimepicker2').val(that.endTime_table);
                that.specifyTime = {
                    startTime: that.jumpData.transportStartDate,
                    endTime: that.jumpData.transportEndDate,
                }
                that.deviceId = that.jumpData.deviceId;
                that.carNumber = that.jumpData.carNumber;
                setTimeout(function(){
                    $("#carNumberSelect2").val(that.carNumber).change();
		            $("#select2-carNumberSelect2-container").attr("title",that.carNumber);
		            $("#select2-carNumberSelect2-container").text(that.carNumber);
                },1000)

            }
            that.load();
        },50)
	}

	isShowDataMse:boolean=false
	//初始化权限按钮
	initBtn() {
		var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_langyun:garbage:single')))
		if (!btnData) {
		  return
		}
		console.log(btnData)
		for (let item of btnData) {
		  if (item.sourceKey === 'garbage:dataMseBtn' && item.parentId) {
			this.isShowDataMse = true
		  }
		}
	  }
	// 接收子组件传递过来的数据
	getSelectTableTime(time){
		this.startTime_table = time.startTime;
		this.endTime_table = time.endTime;
	}
	getSelectCarInfo(val){
		this.deviceId = val.deviceId;
		this.carNumber = val.carNumber;
		this.selectedCompanyId = val.companyId;
		this.selectedCompanyName = val.companyName;
	}
	//表格搜索
	table_search() {
		this.curPage = 1
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//刷新
	refresh(){
	    let timeR = common.getRecentDaysDateTime(1);
        this.specifyTime = {
            startTime: timeR.startTime,
            endTime: timeR.endTime,
        }
        setTimeout(()=>{this.load();},50)
    }
	//初始化加载list数据
	load() {
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				companyId: this.selectedCompanyId,
				deviceId: this.deviceId,
				startTime:this.startTime_table,
				endTime:this.endTime_table,
				searchKey:this.searchKey,
				timeType: this.timeType
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("garbage/garbageForSinglePagelist.html", reqdata).subscribe(data => {
			const exhibitDatas = data.exhibitDatas || []
			this.tableData = exhibitDatas.map(item => {
				item.weight = parseFloat(item.weight).toFixed(2)
				return item
			});
			this.totalCount = data.recordCount;
		})
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//导出报表
	exportData() {
		let parameters = {
			companyId: this.selectedCompanyId,
			deviceId: this.deviceId,
			startTime:this.startTime_table,
			endTime:this.endTime_table,
			searchKey:this.searchKey,
			timeType: this.timeType
		};
		let timeCheck=common.correctTime(parameters,['timeType']);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let paramsName = 'param';
		let _url = config.BaseURL + 'garbage/exportGarbageForSingleDetail.html';
		common.exprotDataFile(parameters,paramsName,_url);
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.deviceId = data.deviceId;
		this.carNumber = data.carNumber;
	}
	//统计弹窗
	censusData: any={
		totalWeight: '',
		num: '',
		maxWeight: '',
		minWeight: ''
	}; //统计数据
	lgModalhide(modal){
		modal.hide();
	}
	census(modal){
		if(!this.deviceId){
			this.jsonApiService.message('请先选择车牌号码');
			return
		}
		if(!this.startTime_table||!this.endTime_table){
			this.jsonApiService.message('起始或结束时间不能为空');
			return
		}
		this.censusData={
			totalWeight: '',
			num: '',
			maxWeight: '',
			minWeight: ''
		}; //统计数据
		modal.show();
		let data = {
			deviceId: this.deviceId,
			startTime:this.startTime_table,
			endTime:this.endTime_table,
			type: '1', //1单次重量明细  2单次重量明细(RFID) 3单桶数据汇总
			timeType: this.timeType
		}
		// let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http_obj("garbage/garbageStatistics.html", data).subscribe(data => {
			if(data.success){
				this.censusData={
					totalWeight: data.data.totalWeight,
					num: data.data.num,
					maxWeight: data.data.maxWeight,
					minWeight: data.data.minWeight
				}; //统计数据

			}
		})
	}


	fileUp: string = '';
	fileToUpload: File = null; //上传文件回调参数
	// 显示数据管理弹框
	showImportModal(modal) {
		// 清空选择的文件
		modal.show();
		this.fileToUpload = null;
	}
	// 关闭数据管理弹窗
	cancelUp(modal) {
		modal.hide();
		this.fileToUpload = null;
	}
	// 下载模板
	load_module() {
		var elemIF = document.createElement("iframe");
		elemIF.src = config.BaseURL + 'resources/template/Garbage-Template.xlsx';
		elemIF.style.display = "none";
		document.body.appendChild(elemIF);
	}
	// 清空input type=file输入框的值
	clearFile() {
		this.fileUp = '';
	}
	//文件上传change回调
	fileChange(files: FileList) {
		this.fileToUpload = files.item(0);
		const isEXCEL = this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || this.fileToUpload.type === "application/vnd.ms-excel";
		if (!isEXCEL) {
			this.jsonApiService.message('上传文件只能是 excel格式!');
			this.fileToUpload = null;
			return;
		}
	}
	//导入submit
	submitData(modal1, modal2, type) {
		let postParam = new FormData();
		postParam.append('file', this.fileToUpload);
		if (!this.fileToUpload) {
			this.jsonApiService.message('请上传文件')
			return false;
		}
		this.jsonApiService.form_http("garbage/uploadGarbageDetail.html", postParam).subscribe(data => {
			if (data.success) {
				modal1.hide();
				this.fileToUpload = null;
				this.load();
			}
		})
	}
	//删除数据
	dataDelete(){
		if(!this.carNumber){
			this.jsonApiService.message("车牌号不能为空！");
			return
		}
		if(!this.startTime_table||!this.endTime_table){
			this.jsonApiService.message("时间不能为空！");
			return
		}
		this.jsonApiService.confirm_message(`确认删除 ${this.carNumber} ${this.startTime_table} 至 ${this.endTime_table} 内的数据吗？` ).then(() => {
			let reqdata = {
				deviceId:this.deviceId,
				timeType:this.timeType,
				startTime:this.startTime_table,
				endTime:this.endTime_table
			};
			this.jsonApiService.http_obj("garbage/deleteGarbageDetail.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
				}
			})
		})
	}
}